import ReconnectingWebSocket from "reconnecting-websocket";
import store from "../store";
import Vue from "vue";
import router from "../router/index";

import { Loading } from "element-ui";

import { Notification } from "element-ui";
export default function createWS() {
  let token = localStorage.getItem("vuex");
  if (!token) {
    router.push({ path: "/login" });
  }
  let url = `${window.WS_BASE_URL}/underwater-sound/systemMsg/${store.state.username}`;
  // 创建一个新的ReconnectingWebSocket实例
  let ws = new ReconnectingWebSocket(url, null, {
    reconnectInterval: 5000, // 重连间隔时间（毫秒）
    maxReconnectAttempts: 10, // 最大重连次数
    debug: true, // 是否记录调试信息
  });
  store.dispatch("setWsInstance", ws);
  store.state.wsInstance.onopen = (event) => {
    window.setInterval(() => {
      if (store.state.wsInstance) {
        store.state.wsInstance.send("1");
      }
    }, 30000);
  };

  store.state.wsInstance.onmessage = (event) => {
    // let weidu = store.state.wsInstancealgresult.filter((e) => {
    //   return e.isunread
    // })
    // let currObj = JSON.parse(event.data)
    // currObj.isunread = true
    // weidu.push(currObj)
    let result = JSON.parse(event.data);

    let loadingInstance = Loading.service({});
    setTimeout(() => {
      loadingInstance.close();
    }, 0);
    Notification.closeAll();
    if (result.flag === "0") {
      Notification.warning({
        title: "提示",
        message: "执行失败",
        position: "top-right",
        offset: 50,
        duration: 0,
      });
      // Vue.prototype.$bus.$message({
      //   message: result.msg,
      //   type: "warning",
      // });
    } else {
      let currARR = result.msg;
      if (result.flag === "1") {
        Notification.success({
          title: "提示",
          message: "计算完毕",
          position: "top-right",
          offset: 50,
          duration: 3000,
        });
        // console.log("执行成功==", currARR);
        let item = JSON.parse(currARR[0]);
        // console.log("第一条===", item);
        item.tabName = getTagName(item.functionName);
        store.commit("SETCURRTABITEM", item);
        Vue.prototype.$bus.$emit("getdata", false);
      }
      store.dispatch("setWsalgresult", currARR);
    }
  };

  store.state.wsInstance.onerror = function (error) {
    console.error("WebSocket Error: ", error);
  };

  store.state.wsInstance.onclose = function (event) {
    if (event.wasClean) {
      console.log("Clean close");
    } else {
      console.error("Unclean close");
    }
    console.log("Code: " + event.code + " Reason: " + event.reason);
  };

  // 获取算法标签上显示的算法名称
  function getTagName(functionName) {
    // lofar=LOFAR、demon=DEMON、detection=信号检测、distinguish=信号识别、estimate=参数估计
    let name = "";
    if (functionName == "lofar") {
      name = "LOFAR";
    } else if (functionName == "demon") {
      name = "DEMON";
    } else if (functionName == "detection") {
      name = "信号检测";
    } else if (functionName == "distinguish") {
      name = "信号识别";
    } else if (functionName == "estimate") {
      name = "参数估计";
    }
    return name;
  }
}
